//
//  YFEmojiKeyBoardView.swift
//  Emoji
//
//  Created by 余仿 on 16/4/17.
//  Copyright © 2016年 yf. All rights reserved.
//

import UIKit

import SnapKit



private  let YFEmojiViewCellID = "YFEmojiViewCellID"



class YFEmojiKeyBoardView: UIView {

    //MARK:表情视图
    private lazy var emojiView:UICollectionView = {

        let flowLayout = UICollectionViewFlowLayout()

        let emojiView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)

        let width = screenWidth

        let height:CGFloat = 226 - 37

        //设置layout相关属性
        flowLayout.itemSize = CGSize(width: width, height: height)
        flowLayout.scrollDirection = .Horizontal
        flowLayout.minimumLineSpacing = 0


        //设置集合相关属性
        emojiView.bounces = false
        emojiView.pagingEnabled = true

        //注册cell
        emojiView.registerClass(YFEmojiCell.self, forCellWithReuseIdentifier: YFEmojiViewCellID)

        emojiView.dataSource = self
        emojiView.delegate = self

        return emojiView
    }()
    //MARK:底部工具条
    private var bottomView:YFBottomBar = YFBottomBar()

    private var currentPage:Int = 0

    //初始化方法
    override init(frame: CGRect) {

        //固定自定义键盘大小
        let rect = CGRect(x: 0, y: 0, width: 0, height: 226)

        super.init(frame: rect)

        setupUI()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MAKR:搭建界面
    func setupUI(){

        addSubview(bottomView)
        addSubview(emojiView)

        bottomView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(37)
        }

        emojiView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(bottomView.snp_top)
        }

        //定义闭包
        bottomView.btnDidSelected = { (index:Int) -> () in

            //集合视图选中对应的组
            let selectedIndexPath = NSIndexPath(forItem: 0, inSection: index - 100)

            self.emojiView.selectItemAtIndexPath(selectedIndexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)

        }

    }

}


// MARK: - 数据源方法
extension YFEmojiKeyBoardView:UICollectionViewDataSource{

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        /*request for number of items before section 1 when there are only 0 sections in the collection view'*/
        return YFEmojiManager.sharedEmojiManager.packages.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return YFEmojiManager.sharedEmojiManager.packages[section].emotions!.count

    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YFEmojiViewCellID, forIndexPath: indexPath) as! YFEmojiCell

        cell.backgroundColor = UIColor.grayColor()

        let emojis = YFEmojiManager.sharedEmojiManager.packages[indexPath.section].emotions![indexPath.item]

        cell.emojis = emojis

        return cell
    }
}

// MARK: - 代理方法
extension YFEmojiKeyBoardView:UICollectionViewDelegate{

    //减速结束
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

        //只有滚动到一定的地方才切换底部工具条的选中状态
        //如何知道当前滚动到哪里呢?
        let index = emojiView.indexPathsForVisibleItems().last

        //获取的当前indexPath.item不太准确,但是获取的组数是准确的
        bottomView.setBtnSelected((index?.section)!)

    }


    // MARK:自定义cell
    class YFEmojiCell:UICollectionViewCell {

        var emojis:[YFEmoji]?{

            didSet{

                //设置数据之前先隐藏
//                for btn in btnArray{
//                    btn.hidden = true
//                }
                //遍历表情数组,给按钮赋值
                if let em = emojis{

                    for (index,emoji) in em.enumerate(){

                        let btn = btnArray[index]

                        btn.emoji = emoji

                    }

                }
            }
        }


        override init(frame: CGRect) {

            super.init(frame: frame)

            setupUI()

        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        //存放表情button的数组
        private var btnArray:[YFEmotionButton] = [YFEmotionButton]()

        func setupUI(){

            let leftMargin:CGFloat = 20
            let emojiBtnWidth = (self.bounds.width - 2 * leftMargin) / 7
            let emojiBtnHeight = emojiBtnWidth
            //添加21个按钮
            for i in 0..<21{

                let emojiBtn = YFEmotionButton()

                contentView.addSubview(emojiBtn)

                //布局
                //计算行和列
                let row = i / 7
                let col = i % 7
                let emojiBtnX = leftMargin + CGFloat(col) * emojiBtnWidth
                let emojiBtnY = CGFloat(row) * emojiBtnHeight

                emojiBtn.frame = CGRect(x: emojiBtnX, y: emojiBtnY, width: emojiBtnWidth, height: emojiBtnHeight)

                //给按钮添加点击事件
                emojiBtn.addTarget(self, action: "emojiBtnDidClick:", forControlEvents: .TouchUpInside)

                //将赋值的时候需要给当前页面中21个cell赋值,
                btnArray.append(emojiBtn)
            }
        }


        //MRAK:表情按钮的点击方法
       @objc  private func emojiBtnDidClick(btn:YFEmotionButton){
            //发通知
            NSNotificationCenter.defaultCenter().postNotificationName(YFEmotionBtnDidClick, object:btn.emoji)
        }
    }
}
